// 路由调试工具
import router from '../router'
import { usePermissions } from '../stores/permission'

/**
 * 添加路由调试命令
 */
export function addRouteDebugCommands() {
  // 调试当前路由状态
  window.debugRoutes = () => {
    console.log('=== 路由调试信息 ===')
    
    const allRoutes = router.getRoutes()
    console.log('所有路由:', allRoutes.map(r => ({ 
      name: r.name, 
      path: r.path, 
      component: r.component?.name || 'Anonymous',
      meta: r.meta
    })))
    
    const { userMenus } = usePermissions()
    console.log('用户菜单数据:', userMenus.value)
    
    console.log('当前路由:', router.currentRoute.value)
    console.log('===================')
  }

  // 测试路由权限
  window.testRoutePermission = (path) => {
    const { userMenus } = usePermissions()
    const { hasRoutePermission } = require('../router/dynamicRoutes')
    
    console.log(`测试路由权限: ${path}`)
    const hasPermission = hasRoutePermission(path, userMenus.value)
    console.log(`结果: ${hasPermission}`)
    
    return hasPermission
  }

  // 查找路由
  window.findRoute = (path) => {
    const allRoutes = router.getRoutes()
    const route = allRoutes.find(r => r.path === path)
    
    console.log(`查找路由: ${path}`)
    if (route) {
      console.log('找到路由:', {
        name: route.name,
        path: route.path,
        component: route.component?.name || 'Anonymous',
        meta: route.meta
      })
    } else {
      console.log('路由未找到')
    }
    
    return route
  }

  // 强制重新加载动态路由
  window.reloadDynamicRoutes = async () => {
    try {
      const { userMenus } = usePermissions()
      const { addDynamicRoutes, clearDynamicRoutes } = await import('../router')
      
      console.log('清除并重新加载动态路由...')
      clearDynamicRoutes()
      
      if (userMenus.value && userMenus.value.length > 0) {
        await addDynamicRoutes(userMenus.value)
        console.log('动态路由重新加载完成')
        window.debugRoutes()
      } else {
        console.log('没有菜单数据，无法加载动态路由')
      }
    } catch (error) {
      console.error('重新加载动态路由失败:', error)
    }
  }

  // 导航到指定路由
  window.navigateTo = (path) => {
    console.log(`导航到: ${path}`)
    router.push(path).catch(error => {
      console.error('导航失败:', error)
    })
  }

  // 检查路由匹配
  window.checkRouteMatch = (path) => {
    const resolved = router.resolve(path)
    console.log(`检查路由匹配: ${path}`)
    console.log('解析结果:', {
      matched: resolved.matched,
      name: resolved.name,
      path: resolved.path,
      meta: resolved.meta
    })
    
    return resolved
  }

  // 诊断刷新404问题
  window.diagnose404 = async (path = null) => {
    const targetPath = path || window.location.pathname
    console.log(`=== 诊断404问题: ${targetPath} ===`)
    
    // 1. 检查用户登录状态
    const { useUserStore } = await import('../stores/user')
    const userStore = useUserStore()
    console.log('用户登录状态:', {
      isLoggedIn: userStore.isLoggedIn,
      isInitialized: userStore.isInitialized,
      currentUser: userStore.currentUser
    })
    
    // 2. 检查token状态
    const token = localStorage.getItem('token')
    const { isTokenExpired } = await import('../utils/tokenUtils')
    console.log('Token状态:', {
      hasToken: !!token,
      isExpired: token ? isTokenExpired(token) : 'N/A'
    })
    
    // 3. 检查权限数据
    const { userMenus } = usePermissions()
    console.log('权限数据:', {
      hasMenus: !!(userMenus.value && userMenus.value.length > 0),
      menuCount: userMenus.value ? userMenus.value.length : 0,
      menus: userMenus.value
    })
    
    // 4. 检查动态路由状态
    const allRoutes = router.getRoutes()
    const dynamicRoutes = allRoutes.filter(r => r.meta?.requiresMenu)
    console.log('动态路由状态:', {
      totalRoutes: allRoutes.length,
      dynamicRoutes: dynamicRoutes.length,
      dynamicRoutePaths: dynamicRoutes.map(r => r.path)
    })
    
    // 5. 检查目标路由
    const targetRoute = allRoutes.find(r => r.path === targetPath)
    console.log('目标路由状态:', {
      exists: !!targetRoute,
      route: targetRoute ? {
        name: targetRoute.name,
        path: targetRoute.path,
        meta: targetRoute.meta
      } : null
    })
    
    // 6. 检查路由权限
    if (userMenus.value) {
      const { hasRoutePermission } = await import('../router/dynamicRoutes')
      const hasPermission = hasRoutePermission(targetPath, userMenus.value)
      console.log('路由权限检查:', {
        hasPermission,
        targetPath
      })
    }
    
    // 7. 提供修复建议
    console.log('=== 修复建议 ===')
    if (!userStore.isLoggedIn) {
      console.log('❌ 用户未登录，请先登录')
    } else if (!token || isTokenExpired(token)) {
      console.log('❌ Token无效，请重新登录')
    } else if (!userMenus.value || userMenus.value.length === 0) {
      console.log('❌ 权限数据为空，尝试运行: window.refreshPermissions()')
    } else if (!targetRoute) {
      console.log('❌ 路由不存在，尝试运行: window.reloadDynamicRoutes()')
    } else {
      console.log('✅ 路由配置正常，可能是其他问题')
    }
    
    console.log('================')
  }

  // 刷新权限数据
  window.refreshPermissions = async () => {
    try {
      console.log('刷新权限数据...')
      const { getUserInfo } = await import('../api/auth')
      const { setUserPermissions } = await import('../stores/permission')
      
      const response = await getUserInfo()
      setUserPermissions(
        response.data.buttons || [],
        response.data.menus || [],
        response.data
      )
      
      console.log('权限数据刷新完成')
      await window.reloadDynamicRoutes()
    } catch (error) {
      console.error('刷新权限数据失败:', error)
    }
  }

  // 模拟页面刷新场景
  window.simulateRefresh = async (path = null) => {
    const targetPath = path || window.location.pathname
    console.log(`模拟页面刷新场景: ${targetPath}`)
    
    // 清除动态路由状态
    const { clearDynamicRoutes } = await import('../router')
    clearDynamicRoutes()
    
    // 重新初始化
    const { useUserStore } = await import('../stores/user')
    const userStore = useUserStore()
    userStore.setInitialized(false)
    
    // 导航到目标路径
    router.push(targetPath).catch(error => {
      console.error('模拟刷新导航失败:', error)
    })
  }

  console.log('路由调试命令已添加:')
  console.log('- window.debugRoutes() - 查看所有路由信息')
  console.log('- window.testRoutePermission(path) - 测试路由权限')
  console.log('- window.findRoute(path) - 查找指定路由')
  console.log('- window.reloadDynamicRoutes() - 重新加载动态路由')
  console.log('- window.navigateTo(path) - 导航到指定路由')
  console.log('- window.checkRouteMatch(path) - 检查路由匹配')
  console.log('- window.diagnose404(path) - 诊断404问题')
  console.log('- window.refreshPermissions() - 刷新权限数据')
  console.log('- window.simulateRefresh(path) - 模拟页面刷新')
}

/**
 * 路由变化监听器
 */
export function setupRouteWatcher() {
  router.afterEach((to, from) => {
    console.log(`路由变化: ${from.path} -> ${to.path}`)
    
    if (to.name === 'NotFound') {
      console.warn('❌ 访问了404页面，可能是路由配置问题')
      console.log('🔧 运行 window.diagnose404() 进行诊断')
      console.log('🔧 或运行 window.debugRoutes() 查看路由状态')
      
      // 自动诊断（仅在开发环境）
      if (import.meta.env.DEV) {
        setTimeout(() => {
          window.diagnose404(to.path)
        }, 1000)
      }
    }
  })

  // 监听路由错误
  router.onError((error) => {
    console.error('路由错误:', error)
    console.log('🔧 运行 window.diagnose404() 进行诊断')
  })
}
